package com.example.demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.Executors;

public class AioHttpServer2 {
    private static final int PORT = 8081;
    private static final int THREAD_POOL_SIZE = 10;

    public static void main(String[] args) throws IOException {
        Long startTime = System.currentTimeMillis();
        // 创建AsynchronousChannelGroup
        AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(THREAD_POOL_SIZE));

        // 创建AsynchronousServerSocketChannel
        AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open(group);
        serverChannel.bind(new InetSocketAddress(PORT));

        // 处理连接事件
        serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
            @Override
            public void completed(AsynchronousSocketChannel socketChannel, Void attachment) {
                serverChannel.accept(null, this); // 接受下一个连接请求
                handleClient(socketChannel); // 处理客户端请求
            }

            @Override
            public void failed(Throwable exc, Void attachment) {
                System.out.println("连接失败：" + exc.getMessage());
            }
        });
        Long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime + " 毫秒");
        // 等待服务器关闭
        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            group.shutdown();
        }

    }

    private static void handleClient(final AsynchronousSocketChannel socketChannel) {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        socketChannel.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
                if (result > 0) {
                    attachment.flip();
                    System.out.println("收到客户端消息：" + new String(attachment.array(), 0, result));
                    socketChannel.read(attachment, attachment, this); // 继续读取数据
                } else if (result == -1) {
                    try {
                        socketChannel.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {
                System.out.println("读取数据失败：" + exc.getMessage());
                try {
                    socketChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
